﻿using System;
using Castle.DynamicProxy;
using Sapit.Base;
using Sapit.Helpers;
using Sapit.Windsor.Attributes;

namespace Sapit.Windsor
{
    public class CircuitBreakerInterceptor : CircuitBreakerBase, IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            var circuitBreaker = AttributeHelper.GetAttributeIfPresent<CircuitBreakerAttribute>(invocation.Method);
            if (circuitBreaker != null)
            {
                Invocation inv = new Invocation() { InvocationTarget = invocation.InvocationTarget, Method = invocation.Method };

                if (ThisInvocationIsShutOff(inv, circuitBreaker))
                {
                    if (ThisInvocationShouldBeTurnedBackOn(inv, circuitBreaker))
                    {
                        TurnThisInvocationBackOn(inv);
                        TryProceed(invocation, inv);
                    }
                    else
                    {
                        PerformShutOffBehavior(invocation, circuitBreaker);
                    }
                }
                else
                {
                    TryProceed(invocation, inv);
                }
            }
            else
            {
                invocation.Proceed();
            }
        }

        private static void TryProceed(IInvocation invocation, Invocation inv)
        {
            try
            {
                invocation.Proceed();
            }
            catch
            {
                RegisterFailure(inv);
                throw;
            }
        }

        private static void PerformShutOffBehavior(IInvocation invocation, CircuitBreakerAttribute circuitBreaker)
        {
            switch (circuitBreaker.BehaviorWhenShutOff)
            {
                case Behavior.Undefined:
                case Behavior.ReturnDefaultValue:
                    invocation.ReturnValue = circuitBreaker.ShutOffReturnValue;
                    break;
                case Behavior.ThrowException:
                    throw new InvalidOperationException(string.Format("{0}", circuitBreaker.ShutOffReturnValue));
                default:
                    invocation.ReturnValue = circuitBreaker.ShutOffReturnValue;
                    break;
            }
        }
    }
}
